package com.ywk.zzh.mongotest.service.impl;

import ch.qos.logback.core.util.StringUtil;
import com.ywk.zzh.mongotest.annotate.GenerateInsert;
import com.ywk.zzh.mongotest.annotate.GenerateUpdate;
import com.ywk.zzh.mongotest.document.User;
import com.ywk.zzh.mongotest.service.UserService;
import com.ywk.zzh.mongotest.vo.Page;
import com.ywk.zzh.mongotest.vo.UserQueryVo;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.regex.Pattern;

@Service
@Slf4j
@AllArgsConstructor
public class UserServiceImpl implements UserService {

    private final MongoTemplate mongoTemplate;

    @Override
    @GenerateInsert
    public void insert(User user) {
        mongoTemplate.save(user);
    }

    @Override
    public Page<User> list(UserQueryVo vo) {
        Query query = new Query();
        if(vo.getId() != null){
            query.addCriteria(Criteria.where("id").is(vo.getId()));
        }
        if(StringUtil.notNullNorEmpty(vo.getName())){
            Pattern pattern = Pattern.compile("^.*" + vo.getName().trim() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("name").regex(pattern));
        }
        if(vo.getAge() != null){
            query.addCriteria(Criteria.where("age").is(vo.getAge()));
        }
        if(StringUtil.notNullNorEmpty(vo.getEmail())){
            Pattern pattern = Pattern.compile("^.*" + vo.getEmail().trim() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("email").regex(pattern));
        }
        // 查询总数
        long total = mongoTemplate.count(query, User.class);

        // 构建排序
        Sort sort = Sort.by(Sort.Direction.DESC, "_id"); // 默认按创建时间降序
        query.with(sort);

        // 构建分页
        int pageNum = vo.getPageNum();
        int pageSize = vo.getPageSize();
        query.skip((long) (pageNum - 1) * pageSize).limit(pageSize);


        // 查询分页数据
        List<User> list = mongoTemplate.find(query, User.class);

        // 构建分页结果
        Page<User> page = new Page<>();
        page.setList(list);
        page.setTotal(total);

        return page;
    }

    @Override
    public User getById(Long id) {
        return mongoTemplate.findById(id, User.class);
    }

    @Override
    @GenerateUpdate
    public void update(User user) {
        mongoTemplate.save(user);
    }
}
